<template>
	<view class="content">
		<view class="bgColor">
			<image src="/static/mine/mineBg.png" mode="widthFix"></image>
		</view>
		<cusHeaderVue titleContent="我的动销员" :showBack="true"></cusHeaderVue>
		<view class="screenBox" :style="{paddingTop: `calc(${scrollerHeight} + 90rpx)`}">
			<!-- 年月选择 -->
			<view class="screenTime" @click="selectMonth">
				{{ selectedMonth }}
				<image src="/static/mine/xiala.png" mode="widthFix"></image>
			</view>
			<!-- 排序方式选择 -->
			<view class="screenTime" @click="selectSort">
				<view class="screenTimeName">
					<image src="/static/mine/xsjepx.png" mode="widthFix"></image>
					{{ sortOptions[sortType - 1] }}
				</view>
				<image src="/static/mine/xiala.png" mode="widthFix"></image>
			</view>
		</view>
		<scroll-view scroll-y="true"
		:style="{height: `calc(100vh - ${scrollerHeight} - 90rpx - 75rpx)`}"
		:refresher-threshold="90"
		>
			<view class="contBox">
				<template v-if="salespersonList.length > 0">
					<view class="contList" v-for="(item, index) in salespersonList" :key="index" 
						@click="toUrl('/pages/mine/salesRepresentative?id=' + item.id)">
						<view class="contTop">
							<view class="contPerson">
								<view class="contPhoto">
									<image v-if="item.avatar" :src="item.avatar" mode="aspectFill"></image>
									<!-- <image v-else src="/static/logo.png" mode="aspectFill"></image> -->
								</view>
								<view class="contTopName">
									{{ item.nickname || '未知' }}
								</view>
							</view>
							<view class="contTopRight">
								指标完成率<text>{{ item.targetAchievementRate || 0 }}</text>%
							</view>
						</view>
						<view class="contNumBox">
							<view class="contNumLi">
								<view class="contNum">
									{{ item.shopNum || 0 }}<text>家</text>
								</view>
								<view class="contMsg">
									负责门店
								</view>
							</view>
							<view class="contNumLi">
								<view class="contNum">
									{{ item.dkNum || 0 }}<text>次</text>
								</view>
								<view class="contMsg">
									打卡次数
								</view>
							</view>
							<view class="contNumLi">
								<view class="contNum">
									{{ item.totalSaleMoney || 0 }}<text>元</text>
								</view>
								<view class="contMsg">
									销售金额
								</view>
							</view>
						</view>
					</view>
				</template>
				<view v-else-if="!isLoading" class="emptyContainer">
					<text class="emptyText">暂无动销员数据</text>
				</view>
			</view>
		</scroll-view>

		<MonthPickerPopup
			ref="monthPickerRef"
			@confirm="onMonthConfirm"
			@cancel="onMonthCancel"
		/>
		
		
	</view>
</template>

<script setup>
import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app';
import { ref, nextTick } from 'vue';
import cusHeaderVue from '@/components/cus-header.vue';
// 如果使用 HBuilderX，通常无需手动引入 UniPopup，但为保险可引入
import UniPopup from '/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
	import MonthPickerPopup from '@/components/MonthPickerPopup.vue';
import { getMyMobilizers } from '@/api/interface.js';



const scrollerHeight = ref('');
// 排序类型：1销售金额 2指标完成率 3打卡次数
const sortType = ref(1);
const sortOptions = ['销售金额排序', '指标完成率排序', '打卡次数排序'];
const salespersonList = ref([]);
const isLoading = ref(false);

// Popup 引用和月份选项


const monthPickerRef = ref(null);
const selectedMonth = ref('');
	

// 获取状态栏高度
const getBarHeight = () => {
	uni.getSystemInfo({
		success: function(res) {
			scrollerHeight.value = res.statusBarHeight + 'px';
		}
	});
};



	// 初始化默认月份
	const initDefaultMonth = () => {
		const now = new Date();
		const year = now.getFullYear();
		const month = now.getMonth() + 1;
		selectedMonth.value = `${year}年${month}月`;
		console.log('默认月份初始化完成:', selectedMonth.value);
	};
	
	// 打开年月选择器
const selectMonth = () => {
	monthPickerRef.value.open();
};
	
	// 选择确认
	const onMonthConfirm = (month) => {
		selectedMonth.value = month;
		// 月份改变时重新获取数据
		loadData();
	};
	
	// 取消（可选处理）
	const onMonthCancel = () => {
		// 可不处理，或做日志等
	};


// 排序选择（安全，只有3项）
const selectSort = () => {
	uni.showActionSheet({
		itemList: sortOptions,
		success: (res) => {
			sortType.value = res.tapIndex + 1;
			// 排序改变时重新获取数据
			loadData();
		},
		fail: () => {
			console.log('用户取消选择排序');
		}
	});
};

// 获取动销员数据
const loadData = async () => {
	console.log('loadData函数执行开始');
	isLoading.value = true;
	try {
		// 确保selectedMonth有值
		if (!selectedMonth.value) {
			console.error('selectedMonth未初始化');
			uni.showToast({
				title: '月份未初始化',
				icon: 'none'
			});
			return;
		}
		
		// 解析月份格式，从 '2024年5月' 转换为 '2024-05'
		const monthParts = selectedMonth.value.split('年');
		const year = monthParts[0];
		const month = monthParts[1].replace('月', '').padStart(2, '0');
		const monthStr = `${year}-${month}`;
		
		const params = {
			monthStr: monthStr,
			// 后端需要 1/2/3 的排序类型，固定传递在合法范围
			sortType: Math.min(Math.max(sortType.value, 1), 3)
		};
		
		console.log('调用getMyMobilizers接口，参数:', params);
		const res = await getMyMobilizers(params);
		console.log('接口返回结果:', res);
		
		if (res.code === 0) {
			salespersonList.value = res.data || [];
			console.log('数据加载成功，共', salespersonList.value.length, '条记录');
		} else {
			console.error('接口返回错误:', res.message);
			uni.showToast({
				title: res.message || '获取数据失败',
				icon: 'none'
			});
		}
	} catch (error) {
		console.error('获取动销员数据异常:', error);
		uni.showToast({
			title: '获取数据失败',
			icon: 'none'
		});
	} finally {
		isLoading.value = false;
		// 关闭下拉刷新状态
		uni.stopPullDownRefresh();
		console.log('loadData函数执行结束');
	}
};



const toUrl = (urlSrc) => {
	uni.navigateTo({ url: urlSrc });
};

// 下拉刷新处理
onPullDownRefresh(() => {
	loadData();
});

onLoad(async () => {
	getBarHeight();
	initDefaultMonth();
	// 确保selectedMonth初始化后立即调用loadData
	console.log('开始调用loadData获取动销员数据');
	await loadData();
});
</script>

<style lang="scss" scoped>
.content {
	width: 100%;
	height: 100vh;
	position: relative;
}

.bgColor {
	width: 100%;
	height: 100%;
	position: absolute;
	z-index: -1;
	top: 0;
	image {
		width: 100%;
		height: 100%;
	}
}

.screenBox {
	display: flex;
	align-items: center;
	justify-content: flex-end;
	padding: 0 22rpx;
	box-sizing: border-box;
	margin-bottom: 20rpx;

	.screenTime {
		height: 55rpx;
		border-radius: 10.26rpx;
		background: #ffffff;
		color: #f79f31;
		font-weight: 400;
		font-size: 25.64rpx;
		padding: 0 15rpx;
		box-sizing: border-box;
		margin-left: 10rpx;
		display: flex;
		align-items: center;
		cursor: pointer;

		image {
			width: 13.46rpx;
			height: 8.33rpx;
			display: block;
			margin-left: 20rpx;
		}

		.screenTimeName {
			display: flex;
			align-items: center;
			image {
				width: 25.64rpx;
				height: 25.64rpx;
				display: block;
				margin-right: 7rpx;
				margin-left: 0;
			}
		}
	}
}

.contBox {
	padding: 0 22rpx;
	box-sizing: border-box;
	padding-bottom: env(safe-area-inset-bottom);
	.contList {
		width: 100%;
		border-radius: 12.82rpx;
		background: #ffffff;
		padding: 34rpx 24rpx;
		box-sizing: border-box;
		margin-bottom: 22rpx;
		.contTop {
			display: flex;
			align-items: center;
			justify-content: space-between;
			.contPerson {
			  display: flex;
			  align-items: center;
			  .contPhoto {
			    width: 93.55rpx;  /* 保持容器宽度 */
			    height: 93.55rpx; /* 保持容器高度 */
			    // background: #f8c79a;
			    border-radius: 20%;
			    overflow: hidden; /* 关键：隐藏图片超出容器的部分 */
			    image {
			      width: 100%;    /* 图片宽度充满容器 */
			      height: 100%;   /* 图片高度充满容器 */
			      object-fit: cover; /* 保持图片比例，裁剪多余部分 */
			    }
			  }
			  .contTopName {
			    /* 保持原有样式 */
			    font-weight: 500;
			    font-size: 33.33rpx;
			    color: #000000;
			    margin-left: 17rpx;
			  }
			}
			.contTopRight {
				width: 216.03rpx;
				height: 50rpx;
				border-radius: 10.26rpx;
				background: #fd503e;
				font-size: 24.36rpx;
				font-weight: 400;
				color: #FFFFFF;
				display: flex;
				align-items: center;
				justify-content: center;
				text {
					font-size: 26.92rpx;
					color: #FFFFFF;
				}
			}
		}
		.contNumBox {
			display: grid;
			grid-template-columns: 1fr 1fr 1fr;
			margin-top: 46rpx;
			.contNumLi {
				display: flex;
				flex-direction: column;
				align-items: center;
				.contNum {
					font-size: 37.18rpx;
					color: #222222;
					text {
						font-size: 23.08rpx;
						margin-left: 5rpx;
					}
				}
				.contMsg {
					font-size: 24.36rpx;
					color: #7F8494;
					margin-top: 8rpx;
				}
			}
		}
	}
}

/* Popup 样式 */
.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 30rpx;
	background: #fff;
	font-size: 28rpx;
	border-bottom: 1px solid #eee;
}

.cancel-btn, .confirm-btn {
	color: #007aff;
}

.title {
	font-weight: bold;
	color: #333;
}

.month-list {
	background: #fff;
}

.month-item {
	padding: 24rpx 30rpx;
	font-size: 30rpx;
	color: #333;
	text-align: center;
	border-bottom: 1px solid #f0f0f0;
}

.month-item:last-child {
	border-bottom: none;
}

.month-item:active {
	background-color: #f8f8f8;
}
</style>